import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useCalendarStore } from '@/stores/modules/calendar'
import userCalendar from '@/hooks/userCalendar'

// 物料种类类型定义
export interface ItemType {
  id: string
  name: string
  replacementCycle: number // 更换周期(月)
  lastReplacementDate: string // 上次更换日期
  groupId: string // 所属分组ID
  order?: number // 排序字段
}

// 分组类型定义
export interface ItemGroup {
  id: string
  name: string
  order: number
}

// 定义 Store
export const useItemStore = defineStore(
  'item',
  () => {

    // 物料种类列表
    const itemTypes = ref<ItemType[]>([])

    // 分组列表
    const groups = ref<ItemGroup[]>([
    ])

    // 当前选中的分组ID
    const currentGroupId = ref('default')

    // 添加物料种类
    const addItemType = (item: Omit<ItemType, 'id'>) => {
      const newItem: ItemType = {
        ...item,
        id: Date.now().toString(),
        order: itemTypes.value.filter(f => f.groupId === item.groupId).length, // 默认排序为当前分组的末尾
      }
      itemTypes.value.push(newItem)
      return newItem.id
    }

    // 更新物料种类
    const updateItemType = (id: string, item: Partial<ItemType>) => {
      const index = itemTypes.value.findIndex(item => item.id === id)
      if (index !== -1) {
        itemTypes.value[index] = { ...itemTypes.value[index], ...item }
      }
    }

    // 删除物料种类
    const removeItemType = (id: string) => {
      const index = itemTypes.value.findIndex(item => item.id === id)
      if (index !== -1) {
        itemTypes.value.splice(index, 1)
        // 删除日历
        const { deleteCalendar } = userCalendar()

        deleteCalendar(id)
      }
    }

    // 添加分组
    const addGroup = (group: Omit<ItemGroup, 'id'>) => {
      let id = `group_${Date.now()}`
      const newGroup: ItemGroup = {
        ...group,
        id: id,
      }
      groups.value.push(newGroup)
      setCurrentGroup(id)
    }

    // 更新分组
    const updateGroup = (id: string, group: Partial<ItemGroup>) => {
      const index = groups.value.findIndex(item => item.id === id)
      if (index !== -1) {
        groups.value[index] = { ...groups.value[index], ...group }
      }
    }

    // 删除分组
    const removeGroup = (id: string) => {
      // 不能删除默认分组
      if (id === 'default') return

      const index = groups.value.findIndex(item => item.id === id)
      if (index === -1) {
        return
      }
      groups.value.splice(index, 1)
      // 删除产品
      itemTypes.value.forEach(item => {
        if (item.groupId === id) {
          removeItemType(item.id)
        }
      })
    }

    // 设置当前分组
    const setCurrentGroup = (id: string) => {
      currentGroupId.value = id
    }

    // 获取当前分组的物料种类
    const getCurrentGroupItems = () => {
      return itemTypes.value
        .filter(item => item.groupId === currentGroupId.value)
        .sort((a, b) => (a.order || 0) - (b.order || 0))
    }

    // 更新分组排序
    const updateGroupOrder = (groupIds: string[]) => {
      groupIds.forEach((id, index) => {
        const group = groups.value.find(g => g.id === id)
        if (group) {
          group.order = index
        }
      })
    }

    // 计算物料剩余天数
    const calculateRemainingDays = (item: ItemType) => {
      const lastDate = new Date(item.lastReplacementDate)
      lastDate.setMonth(lastDate.getMonth() + item.replacementCycle)

      const today = new Date()
      const diffTime = lastDate.getTime() - today.getTime()
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      return diffDays > 0 ? diffDays : 0
    }

    // 计算物料剩余月份和天数
    const calculateRemainingTime = (item: ItemType) => {
      const remainingDays = calculateRemainingDays(item)
      const months = Math.floor(remainingDays / 30)
      const days = remainingDays % 30
      return { months, days, remainingDays }
    }

    // 更换物料
    const replaceItem = (id: string) => {
      const item = itemTypes.value.find(item => item.id === id)
      if (item) {
        item.lastReplacementDate = new Date().toISOString()
      }
    }

    // 更新物料排序
    const updateItemOrder = (itemIds: string[]) => {
      itemIds.forEach((id, index) => {
        const item = itemTypes.value.find(f => f.id === id)
        if (item) {
          item.order = index
        }
      })
    }

    return {
      itemTypes,
      groups,
      currentGroupId,
      addItemType,
      updateItemType,
      removeItemType,
      addGroup,
      updateGroup,
      removeGroup,
      setCurrentGroup,
      getCurrentGroupItems,
      updateGroupOrder,
      updateItemOrder,
      calculateRemainingDays,
      calculateRemainingTime,
      replaceItem: replaceItem,
    }
  },
  // 配置持久化
  {
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)